import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:viser_remit/data/controller/home/home_controller.dart';
import 'package:viser_remit/data/model/kyc/kyc_response_model.dart';
import 'package:viser_remit/data/model/send_money/send_money_save_response_model.dart';
import 'package:viser_remit/data/model/send_money_save/send_money_save_model.dart';
import 'package:viser_remit/view/components/snack_bar/show_custom_snackbar.dart';

import '../../../core/utils/method.dart';
import '../../../core/utils/my_strings.dart';
import '../../../core/utils/url_container.dart';
import '../../model/global/response_model/response_model.dart';
import 'package:http/http.dart' as http;
import '../../services/api_client.dart';
import '../kyc/kyc_repo.dart';

class SendMoneyRepo {
  ApiClient apiClient;

  SendMoneyRepo({required this.apiClient});

  Future<ResponseModel> getSendMoneyData() async {
    String url = "${UrlContainer.baseUrl}${UrlContainer.sendMoneyEndpoint}";
    ResponseModel responseModel = await apiClient.request(url, Method.getMethod, null, passHeader: true);
    return responseModel;
  }

  getServiceFormData() async {
    String url = "${UrlContainer.baseUrl}${UrlContainer.kycFormUrl}";
    ResponseModel responseModel = await apiClient.request(url, Method.postMethod, {"service_id": 9}, passHeader: true, isOnlyAcceptType: true);
    return responseModel;
  }

  saveSendMoneyDataToServer(SendMoneySaveModel model, List<KycFormModel> list) async {
    var saveData = await saveSendMoneyData(model, list);
    if (saveData.statusCode == 200) {
      SendMoneySaveResponseModel sendMoneySaveResponseModel = SendMoneySaveResponseModel.fromJson(jsonDecode(saveData.responseJson));
      return sendMoneySaveResponseModel;
    } else {
      CustomSnackBar.error(errorList: [saveData.message]);
    }
  }

  List<Map<String, String>> fieldList = [];
  List<ModelDynamicValue> filesList = [];

  Future<ResponseModel> saveSendMoneyData(SendMoneySaveModel model, List<KycFormModel> list) async {
    try {
      apiClient.initToken();
      await modelToMap(list);
      String url = '${UrlContainer.baseUrl}${UrlContainer.sendMoneySaveEndPoint}';

      var request = http.MultipartRequest('POST', Uri.parse(url));

      Map<String, String> finalMap = {};

      for (var element in fieldList) {
        finalMap.addAll(element);
      }

      finalMap['sending_amount'] = model.sendingAmount;
      finalMap['sending_country'] = model.sendingCountry;
      finalMap['recipient_amount'] = model.recipientAmount;
      finalMap['recipient_country'] = model.recipientCountry;
      finalMap['source_of_funds'] = model.sourceOfFunds;
      finalMap['sending_purpose'] = model.sendingPurpose;
      finalMap['payment_type'] = model.paymentType;
      finalMap['recipient[name]'] = model.recipientName;
      finalMap["recipient[mobile]"] = model.recipientMobile;
      finalMap["recipient[email]"] = model.recipientEmail;
      finalMap["recipient[address]"] = model.recipientAddress;
      finalMap["save_recipient"] = model.saveRecipient;

      if (Get.find<HomeController>().isAgentSelected) {
        finalMap["delivery_method"] = '0';
      } else {
        finalMap["delivery_method"] = model.deliveryMethod;
        finalMap["service"] = model.service;
      }

      request.headers.addAll(<String, String>{'Authorization': 'Bearer ${apiClient.token}'});

      if (kDebugMode) {
        print('token: ${apiClient.token}');
      }

      for (var file in filesList) {
        request.files.add(http.MultipartFile(file.key ?? '', file.value.readAsBytes().asStream(), file.value.lengthSync(), filename: file.value.path.split('/').last));
      }

      request.fields.addAll(finalMap);
      http.StreamedResponse response = await request.send();

      String jsonResponse = await response.stream.bytesToString();

      // return sendMoneySaveResponseModel;
      return ResponseModel(true, MyStrings.success.tr, 200, jsonResponse);
    } on SocketException {
      return ResponseModel(false, MyStrings.noInternet.tr, 503, '');
    } on FormatException {
      return ResponseModel(false, MyStrings.badResponseMsg.tr, 400, '');
    } catch (e) {
      return ResponseModel(false, MyStrings.somethingWentWrong.tr, 499, '');
    }
  }

  Future<dynamic> modelToMap(List<KycFormModel> list) async {
    for (var e in list) {
      if (e.type == 'checkbox') {
        if (e.cbSelected != null && e.cbSelected!.isNotEmpty) {
          for (int i = 0; i < e.cbSelected!.length; i++) {
            fieldList.add({'${e.label}[$i]': e.cbSelected![i]});
          }
        }
      } else if (e.type == 'file') {
        if (e.imageFile != null) {
          filesList.add(ModelDynamicValue(e.label, e.imageFile!));
        }
      } else {
        if (e.selectedValue != null && e.selectedValue.toString().isNotEmpty) {
          fieldList.add({e.label ?? '': e.selectedValue});
        }
      }
    }
  }
}
